<template>
  <div id="continue">
    <div class="login-wrapper">
      <div class="img-wrapper">
        <img src="@/assets/images/login.jpg" alt="">
      </div>
      <div class="form-wrapper">
        <h2>欢迎回来!</h2>
        <p>请输入你的账户，登录聊天系统</p>
        <div class="input-wrapper">
          <input type="text" placeholder="用户手机号" v-model="loginInfo.username"/>
        </div>
        <div class="input-wrapper">
          <input type="password" placeholder="用户密码" v-model="loginInfo.password"/>
        </div>
        <button @click="login">登录</button>
        <p class="tip">
          不存在账户? <a href="/register">立即注册</a>
        </p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">

import {getCurrentInstance, reactive} from 'vue';
import {ElLoading, ElMessage} from "element-plus";
//用户登录
import {loginService} from '@/server/userService';
//缓存
import localstorage from '@/utils/storage';
import {useRoute, useRouter} from 'vue-router';

//上下文
const {appContext} = getCurrentInstance();
//路由
const router = useRouter();

//获取重定向参数
const route = useRoute();
let redirect = '/';
if (route.query.hasOwnProperty('redirect')) {
  redirect = decodeURIComponent(route.query.redirect);
}
console.log(redirect);

//用户注册信息
let loginInfo = reactive({
  username: '',
  password: '',
});

function login() {
  //判断
  if (!loginInfo.username) {
    ElMessage({
      message: '请输入用户名!',
      type: 'warning',
    }, appContext)
    return;
  }

  if (!loginInfo.password) {
    ElMessage({
      message: '请输入用户密码!',
      type: 'warning',
    }, appContext)
    return;
  }

  const loadingInstance1 = ElLoading.service();
  loginService(loginInfo).then((res) => {
    setTimeout(loadingInstance1.close, 500);
    const data = res.data;
    if(data.code) {
      ElMessage.info(data.msg);
      return;
    }
    ElMessage.success('登录成功');
    //保存用户token
    localstorage.set('token',data.data.token,2592000);
    //跳转去首页
    setTimeout(()=>{
      router.push(redirect);
    },1500);
  })
}
</script>

<style scoped lang="scss">
@use "login";
</style>